import { Alert, Button, Form, Input, Layout, Row, Space } from 'antd'
import store from 'store'

import { useModel } from '@umijs/max'

// 默认配置
import { defaultConfig } from '@/config'

import styles from './index.less'

const FormItem = Form.Item
const { Footer } = Layout

export default function Login() {
  const { login, loading, error, clearError } = useModel('login', (model) => ({
    login: model.login,
    loading: model.loading,
    error: model.error,
    clearError: model.clearError,
  }))

  const handleOk = async (values: any) => {
    const region_id = store.get('region_id')

    login({
      payload: {
        ...values,
        region_id,
      },
    })
  }

  const handleInputChange = () => {
    if (error) {
      clearError()
    }
  }

  return (
    <>
      <div className={styles.form}>
        <div className={styles.logo}>
          <img alt="logo" src={defaultConfig.logoPath} />
          <span>{defaultConfig.siteName}</span>
        </div>
        <Form onFinish={handleOk}>
          <FormItem name="username" rules={[{ required: true, message: '请输入用户名' }]} hasFeedback>
            <Input placeholder="用户名" onChange={handleInputChange} />
          </FormItem>
          <FormItem name="password" rules={[{ required: true, message: '请输入密码' }]} hasFeedback>
            <Input type="password" placeholder="密码" onChange={handleInputChange} />
          </FormItem>
          {error && <Alert message={error} type="error" style={{ marginBottom: 16 }} />}
          <Row>
            <Button type="primary" htmlType="submit" loading={loading}>
              登录
            </Button>
          </Row>
        </Form>
      </div>
      <div className={styles.footer}>
        <Footer style={{ textAlign: 'center', padding: '20px' }}>
          <Space direction="vertical">{defaultConfig.copyright}</Space>
        </Footer>
      </div>
    </>
  )
}
